package controleur;

import beans.CliClients;
import beans.CmdCommande;
import beans.CmdDetailCmde;
import beans.DetailCommande;
import beans.Livre;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import traitements.AfficherCompte;
import traitements.Commande;
import traitements.Connexion;
import traitements.GererErreurs;
import traitements.GererInscription;
import traitements.GererLivre;

@WebServlet(name = "ctrl", urlPatterns = {
    "/ctrl/*"
})
public class Controler extends HttpServlet {

    public static final String ATT_CLIENT = "client";
    public static final String ATT_FORM = "form";
    public static final String ATT_ADR = "adresses";
    public static final String ATT_PHO = "phones";
    public static final String ATT_NVCLIENT = "nvClient";
    // Constantes HLA ;-)
    public static final int CONSTANT_Page = 5; // Nbre de ligne par page par défault

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();
        GererInscription g = new GererInscription();
        CliClients nvClient = new CliClients();
        
        /* Section Login - switch */
        Cookie cookiePresent = getCookie(request, ATT_CLIENT);

        if ((cookiePresent != null) && (request.getParameter("action").equals("home"))) {
            Connexion con = new Connexion();
            CliClients client = con.autoConnect(Integer.parseInt(cookiePresent.getValue()));
            session.setAttribute(ATT_CLIENT, client);
            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
        }

        if ((cookiePresent != null) && (request.getParameter("action").equals("bye"))) {
            session.setAttribute(ATT_CLIENT, null);
            cookiePresent.setValue("");
            cookiePresent.setMaxAge(0);
            response.addCookie(cookiePresent);
            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
        }
        if ((cookiePresent == null) && (request.getParameter("action").equals("home"))) {

            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("connect")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

        }

        if (request.getParameter("action").equals("bye")) {
            session.setAttribute(ATT_CLIENT, null);
            if (cookiePresent != null) {
                cookiePresent.setValue(null);
                cookiePresent.setMaxAge(0);
            }
            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").include(request, response);/* forward(request, response);*/
        }

        if (request.getParameter("action").equals("connexion")) {
            Connexion con = new Connexion();
            CliClients client = con.ConnecterCli(request);
            request.setAttribute(ATT_CLIENT, client);
            request.setAttribute(ATT_FORM, con);
            Cookie compteur = getCookie(request, "compteur");
            if (compteur == null) {
                compteur = new Cookie("compteur", "1");
            }
            if (con.getErreurs().isEmpty()) {
                /* Si aucune erreur */
                if (request.getParameter("cc") != null) {
                    Cookie cc = new Cookie(ATT_CLIENT, "" + client.getCliId());
                    cc.setMaxAge(60 * 60);
                    response.addCookie(cc);
                }
                compteur.setValue("1");
                compteur.setMaxAge(0);
                response.addCookie(compteur);
                session.setAttribute(ATT_CLIENT, client);
                this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
            } else {
                /* Sinon ré-affichage du formulaire avec les erreurs */
                session.setAttribute(ATT_CLIENT, null);
                int i = Integer.parseInt(compteur.getValue());
                compteur.setValue(++i + "");
                if (i > 3) {
                    request.setAttribute("tentative", true);
                }
                compteur.setMaxAge(3 * 60);
                response.addCookie(compteur);
                this.getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
            }
        }

        if (request.getParameter("action").equals("voircompte")) {
            CliClients client = (CliClients) session.getAttribute(ATT_CLIENT);
            AfficherCompte tmp = new AfficherCompte();
            if (client != null) {
                ArrayList listeAdr = tmp.getAdresses(client.getCliId());
                ArrayList listePhones = tmp.getPhones(client.getCliId());
                session.setAttribute(ATT_ADR, listeAdr);
                session.setAttribute(ATT_PHO, listePhones);
            }
            this.getServletContext().getRequestDispatcher("/WEB-INF/affichagecompte.jsp").forward(request, response);
        }

        /**
         * **********************************************************************************
         */
        /*   HIPPOLYTE : Création du compte client
         /*   
         /*
         /*************************************************************************************/
        
        
        
        
        if(request.getParameter("action").equals("creation")){
           
            this.getServletContext().getRequestDispatcher("/WEB-INF/inscription.jsp").forward(request, response);
        } 

        if (request.getParameter("action").equals("verification")) { 
            request.setAttribute("ATT_NVLOG", true);
            nvClient = g.verifierNvLog(request);
            if (!g.getErreurs().isEmpty()) {
                request.setAttribute("ATT_NVLOG", false);
            }
            request.setAttribute(ATT_NVCLIENT, nvClient);
            request.setAttribute(ATT_FORM, g);
            this.getServletContext().getRequestDispatcher("/WEB-INF/inscription.jsp").forward(request, response);
        }  
        if (request.getParameter("action").equals("inscription")) {
            request.setAttribute("ATT_NVLOG", true);
            nvClient = g.verifierChamps(request);
            request.setAttribute(ATT_NVCLIENT, nvClient);
            request.setAttribute(ATT_FORM, g);
            //this.getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
            if (g.getErreurs().isEmpty()) {
                int resultat = g.creerClients(nvClient);
                if (resultat == 0) {
                    this.getServletContext().getRequestDispatcher("/WEB-INF/inscription.jsp").forward(request, response);
                } else {
                    this.getServletContext().getRequestDispatcher("/WEB-INF/confirmation.jsp").forward(request, response);
                }

            } 
            else {
                this.getServletContext().getRequestDispatcher("/WEB-INF/inscription.jsp").forward(request, response);
            }
        }
         
        
        if ((session.getAttribute(ATT_CLIENT) != null) && (request.getParameter("action").equals("modification"))) {
            
             this.getServletContext().getRequestDispatcher("/WEB-INF/modification.jsp").forward(request, response);
        }
        
         /////////////////////////////////////////////////////////////////////////////////////////////
        //Historique des commandes by Vincent


        CliClients client = (CliClients) session.getAttribute(ATT_CLIENT);



        if ("vueCommande".equals(request.getParameter("action"))) {

            if (session.getAttribute(ATT_CLIENT) == null) {
                request.setAttribute("connected", false);
                getServletContext().getRequestDispatcher("/WEB-INF/vueCommande.jsp").include(request, response);
            } else {

                request.setAttribute("connected", true);
                Commande mesCommandes = (Commande) session.getAttribute("myCommandes");
                if (mesCommandes == null) {
                    mesCommandes = new Commande();
                    session.setAttribute("myCommandes", mesCommandes);
                }



                request.setAttribute("lesLivres", mesCommandes.listeCommandes(client.getCliId()));

                getServletContext().getRequestDispatcher("/WEB-INF/vueCommande.jsp").include(request, response);
            }
        }

        if ("vueDetailCmde".equals(request.getParameter("action"))) {


            Commande mesCommandes = (Commande) session.getAttribute("myCommandes");
            ArrayList<CmdDetailCmde> leDetailCommandes = mesCommandes.detailCommandes(Integer.valueOf(request.getParameter("cmdId")));
            session.setAttribute("leDetailCommandes", leDetailCommandes);

            this.getServletContext().getRequestDispatcher("/WEB-INF/vueDetailCmde.jsp").forward(request, response);
        }


        if (request.getParameter("action").equals("detaillivre")) {

            GererLivre tmp;
            try {
                tmp = new GererLivre();
                Livre livre = tmp.afficherLivre(Integer.valueOf(request.getParameter("livreid")));
                request.setAttribute("detaillivre", livre);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            }

            this.getServletContext().getRequestDispatcher("/WEB-INF/detaillivre.jsp").forward(request, response);
        }

        /////////////////////////////////////////////////////////////////////////////////////////////
        // Section LIVRE - HLA ;-)
        /////////////////////////////////////////////////////////////////////////////////////////////
        if ((request.getParameter("action").equals("catalogue"))
                || (request.getParameter("action").equals("backward"))
                || (request.getParameter("action").equals("forward"))
                || (request.getParameter("action").equals("definirNbLignesParPage"))
                || (request.getParameter("action").equals("search"))) {

            GererLivre gererLivre;
            ArrayList<Livre> listeLivres;
            Map<String, String> erreurs = new HashMap<String, String>();

            String VUE = "/WEB-INF/listerLivres.jsp";
            PrintWriter out = response.getWriter();

            String val = "";
            int page = CONSTANT_Page;  // Nbre de lignes par page par default (En Integer !!!)
            int offset = 0;
            String sens = "forward";
            //------------------------------------------------------------------------
            //  Si l'on vient du catalogue on repagine depuis de début de la table
            //-----------------------------------------------------------------------
            if (request.getParameter("action").equals("catalogue")) {
                try {
                    gererLivre = new GererLivre();
                    val = "";
                    // On réinitialise les infos livres de la session
                    session.setAttribute("livres", null);
                    session.setAttribute("page", null);
                    session.setAttribute("val", null);
                    session.setAttribute("offset", null);
                    // on lit les livres
                    listeLivres = gererLivre.searchLivres(offset, page, val);
                    // On stocke de la liste de livres dans l'objet session
                    session.setAttribute("livres", listeLivres);
                    // On dispatch vers la JSP
                    this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
                    return;
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //------------------------------------------------------------------------
            // Gestion du formulaire de la JSP            
            // --> Si j'ai changé le nbre de lignes par page ds le Formulaire, je le monte en session
            //------------------------------------------------------------------------
            if ("definirNbLignesParPage".equalsIgnoreCase(request.getParameter("action"))) {
                String nbLignesParPage = request.getParameter("INPUT_NbLignesParPage").trim();
                //----------------------------------------------------------
                // Validation du champ INPUT_NbLignesParPage du formulaire
                //----------------------------------------------------------
                try {
                    GererErreurs gererErreurs = new GererErreurs();
                    gererErreurs.validationNbLignesParPage(nbLignesParPage);
                } catch (Exception ex) {
                    erreurs.put("INPUT_NbLignesParPage", ex.getMessage());
                }
                //----------------------------------------------------------
                // Validation de la saisie et montée en session
                //----------------------------------------------------------
                if (erreurs.isEmpty()) {    // S'il est correctement saisi, on le monte en session
                    page = Integer.parseInt(nbLignesParPage);
                    session.setAttribute("page", page);
                    request.setAttribute("INPUT_NbLignesParPage", nbLignesParPage);
                } else { // Erreur de saisie on affiche le message d'erreur...
                    request.setAttribute("erreurs", erreurs);
                    this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
                    return;
                }
            }
            //------------------------------------------------------------------------
            // On récupere les infos livres en session si elles existent
            //------------------------------------------------------------------------
            if (session.getAttribute("page") != null) {
                page = (Integer) session.getAttribute("page");
                request.setAttribute("INPUT_NbLignesParPage", page);
            } else {
                page = CONSTANT_Page;
                request.setAttribute("INPUT_NbLignesParPage", Integer.toString(CONSTANT_Page));
            }
            if (session.getAttribute("offset") != null) {
                offset = (Integer) session.getAttribute("offset");
            } else {
                offset = 0;
            }
            //------------------------------------------------------------------------
            // Gestion des Href de la JSP (J'ai cliqué sur avancer ou reculer)
            //------------------------------------------------------------------------
            try {
                //--------------------------------------------------------------------
                // Recuperation des parametres de request (sens="forward"/"backward")
                //--------------------------------------------------------------------
                if (request.getParameter("action") != null) {
                    if (request.getParameter("action").equalsIgnoreCase("forward") || request.getParameter("action").equalsIgnoreCase("backward")) {
                        sens = (String) request.getParameter("action");
                    }
                }
                //--------------------------------------------------------------------
                // On a demandé une recherche, on recupere le parametre de recherche
                //--------------------------------------------------------------------
                if (request.getParameter("type") != null) {
                    if (request.getParameter("type").equals("auteur")) {
                        this.getServletContext().getRequestDispatcher("/WEB-INF/bg.jsp").forward(request, response);
                        return;
                    }
                }

                if (request.getParameter("action").equals("search") || session.getAttribute("val") != null) {
                    if (request.getParameter("val") != null) {
                        val = request.getParameter("val").trim();
                        session.setAttribute("val", val);  // On monte le parametre de recherche en session                      
                    } else {    //On recupere le parametre de recherche de la session s'il existe...
                        val = (String) session.getAttribute("val");
                    }
                }
                //--------------------------------------------------------------------
                // Gestion avant/arriere
                //--------------------------------------------------------------------
                System.out.println("SENS =====>" + request.getParameter("action") + ", " + offset + ", " + page);
                if (request.getParameter("action").equals("backward")) {
                    offset = offset - page;
                } else {
                    if (request.getParameter("action").equals("forward")) {
                        offset = offset + page;
                    } else {
                        offset = 0;
                    }
                }
                if (offset < 0) {
                    offset = 0;
                }
                session.setAttribute("offset", offset);
                //--------------------------------------------------------------------
                // Récuperation des livres en base de donnée
                //--------------------------------------------------------------------
                gererLivre = new GererLivre();

                listeLivres = gererLivre.searchLivres(offset, page, val);
                session.setAttribute("livres", listeLivres);// Stockage de la liste de livres dans l'objet session 

                //--------------------------------------------------------------------

            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            }
            //--------------------------------------------------------------------
            //  Appel de la JSP d'affichage...
            //--------------------------------------------------------------------

            this.getServletContext()
                    .getRequestDispatcher(VUE).forward(request, response);
        }

        /////////////////////////////////////////////////////////////////////////////////////////////

        if (request.getParameter("action").equals("detaillivre")) {

            GererLivre tmp;
            try {
                tmp = new GererLivre();
                Livre livre = tmp.afficherLivre(Integer.valueOf(request.getParameter("livreid")));
                request.setAttribute("detaillivre", livre);


            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Controler.class
                        .getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Controler.class
                        .getName()).log(Level.SEVERE, null, ex);
            }

            this.getServletContext().getRequestDispatcher("/WEB-INF/detaillivre.jsp").forward(request, response);
        }

        /////////////////////////////////////////////////////////////////////////////////////////////
        // Section CATALOGUE - Loïc ;-)  // alt method
        /////////////////////////////////////////////////////////////////////////////////////////////

        if (request.getParameter("action").equals("cata")) {
            int page = 1;
            int ligpage = 5;
            int nbpages = 0;
            GererLivre tmp;
            try {
                tmp = new GererLivre();
                int nbLivres = tmp.getNbLivres();

                page = Integer.parseInt(request.getParameter("page"));

                ArrayList<Livre> listing = tmp.getPgLivres((page - 1) * ligpage, ligpage);
                System.out.println(listing);

                nbpages = (int) Math.ceil(nbLivres * 1.0 / ligpage);
                request.setAttribute("listing", listing);
                request.setAttribute("nbpages", nbpages);
                request.setAttribute("page", page);
                this.getServletContext().getRequestDispatcher("/WEB-INF/catalogue.jsp").forward(request, response);



            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Controler.class
                        .getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Controler.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
        }





        /* Section footer - pages générales */
        if (request.getParameter("action").equals("cgv")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/cgv.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("legal")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/legal.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("faq")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/faq.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("contact")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/contact.jsp").forward(request, response);
        }
    }

    /**
     * Méthode utilitaire gérant la récupération de la valeur d'un cookie donné
     * depuis la requête HTTP.
     */
    private static Cookie getCookie(HttpServletRequest request, String nom) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie != null && nom.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
